package qj.util.tcp;

import java.net.Socket;

import qj.util.ThreadUtil4;
import qj.util.funct.P0;

public class HandshakeSocket extends TextSocket {

	private P0 handshakeFailListener;

//	/** Logger **/
//	private static final Log log = LogFactory.getLog(HandshakeSocket.class);

	private Handshaker handshaker;
	
	public HandshakeSocket(Socket sk) {
		super(sk);
	}
	
	public synchronized void close() {
		super.close();
		if (handshaker!=null) {
			handshaker.stop();
			handshaker = null;
		}
	}

	public void startHandshake(int rate) {
		handshaker = new Handshaker(this, handshakeFailListener, rate);
		Thread handshakeThread = new Thread(handshaker);
		handshakeThread.setDaemon(true);
		handshakeThread.start();
	}
	
	static class Handshaker implements Runnable {
		int rate = 10000;
		
		HandshakeSocket sk;
		P0 handshakeFailListener;
		boolean running = true;
		public Handshaker(HandshakeSocket sk, P0 handshakeFailListener, int rate) {
			this.sk = sk;
			this.handshakeFailListener = handshakeFailListener;
			this.rate = rate;
		}

		public void run() {
			do  {
				ThreadUtil4.sleep(rate);
				if (!running) {
//					log.debug("Terminated");
					return;
				}
//				log.debug("Handshaking...");
			} while (sk.isAlive() && "Ok".equals(sk.read("Ok?", 1000)));
			sk.close();
		}
		
		public void stop() {
			running = false;
		}
	}
}
